<?php
/**
 * Created by PhpStorm.
 * User: ChengChaogui
 * Date: 2016/11/25
 * Time: 16:07
 */

namespace App\Framework\Helper;

class TextHelper
{
    //基本字符
    private static $base_char = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    //移动设备标签
    private static $mobile_device_tag = ["android", "iphone", "ipad", "symbian", "windowsphone", "ipod", "blackberry", "windows ce"];

    /**
     * 获取指定长度的随机字符串，包含大小写字母和数字
     * @param $len
     * @return int|string
     */
    public static function getRandomStr($len)
    {
        $max = count(self::$base_char);
        $result = '';
        for ($i = 0; $i < $len; $i++) {
            $num = rand(0, $max - 1);
            $result .= self::$base_char[$num];
        }

        return $result;
    }

    /**
     * 生成一个唯一字符串(uuid)
     * @param string $prefix
     * @return string
     */
    public static function getUuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-';
        $uuid .= substr($chars, 8, 4) . '-';
        $uuid .= substr($chars, 12, 4) . '-';
        $uuid .= substr($chars, 16, 4) . '-';
        $uuid .= substr($chars, 20, 12);
        return $prefix . $uuid;
    }

    /**
     * 检查访问设备是否为移动设备
     * @param $agent
     * @return bool
     */
    public static function isMobileDevice($agent)
    {
        $nav = strtolower($agent);
        foreach (self::$mobile_device_tag as $tag) {
            if (strpos($nav, $tag) != false) {
                return true;
            }
        }

        return false;
    }

    /**
     * 将查询字符串的值截取并写入数组
     * 将查询字符串的值截取并写入数组
     * @param $arr
     * @param $character
     * @return array
     */
    public static function urlQueryToArray($arr, $character)
    {
        $ex_arr = explode('&', $arr);
        $result = [];
        foreach ($ex_arr as $k => $v) {
            array_push($result, ltrim($v, $character . '='));
        }

        return $result;
    }
}